 package ru.sbrf.ufs.bh.pt.common.integration.service.report;
 
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
 import ru.sbrf.ufs.bh.pt.common.integration.exception.DaServiceException;
 import ru.sbrf.ufs.bh.pt.common.integration.service.logger.EribLogger;
 import ru.sbrf.ufs.bh.pt.common.integration.service.report.dto.Body;
 import ru.sbrf.ufs.bh.pt.common.integration.service.report.dto.PlatformReportRenderRq;
 import ru.sbrf.ufs.bh.pt.common.integration.service.report.dto.Request;
 import ru.sbrf.ufs.bh.pt.common.utils.Utils;
 import ru.sbrf.ufs.platform.core.jaxrs.response.model.BaseResponse;
 import ru.sbrf.ufs.platform.core.jaxrs.response.model.Error;
 import ru.sbrf.ufs.platform.httpclient.JsonRestClient;
 import ru.sbrf.ufs.platform.httpclient.ResponseTypeReference;
 
 import javax.annotation.Nonnull;
 import java.util.Map;
 
 import static javax.xml.bind.DatatypeConverter.parseBase64Binary;
 
 /**
  * Сервис печати
  */
 public class ReportService {
 
     private static final String SERVICE_NAME = "ReportService";
     private final JsonRestClient jsonRestClient;
     private final ReportServiceConfig config;
     @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
     @Autowired
     @Qualifier("ptEribLogger")
     private EribLogger eribLogger;
 
     public ReportService(JsonRestClient jsonRestClient, ReportServiceConfig config) {
         this.jsonRestClient = jsonRestClient;
         this.config = config;
     }
 
     /**
      * @param attributes данные для заполнения шаблона
      * @return байты PDF-файла
      */
     public byte[] renderPDF(String templateName, Map<String, Object> attributes) {
         PlatformReportRenderRq renderRq = makeRenderRequest(templateName, attributes);
         Body body = getReport(renderRq);
         if (StringUtils.isNotEmpty(body.getData())) {
             return decodeBase64(body.getData());
         }
         return new byte[0];
     }
 
     private PlatformReportRenderRq makeRenderRequest(String templateName, Map<String, Object> attributes) {
         return new PlatformReportRenderRq()
                 .withRequest(new Request()
                         .withTemplateCode(templateName)
                         .withChannel(config.getReportChannel())
                         .withSubsystem(config.getReportSystem())
                         .withZone(config.getReportZone()))
                 .withOutputType(PlatformReportRenderRq.OutputType.PDF)
                 .withJsonString(Utils.serializeToJson(attributes));
     }
 
     private byte[] decodeBase64(String base64) {
         return parseBase64Binary(base64);
     }
 
     @Nonnull
     private Body getReport(PlatformReportRenderRq request) {
         long start = System.currentTimeMillis();
         BaseResponse<Body> response = jsonRestClient.post(config.getReportPath(), request, new ResponseTypeReference<BaseResponse<Body>>() {
         });
         if (!Boolean.TRUE.equals(response.getSuccess())) {
             Error error = response.getError();
             if (error != null) {
                 throw new DaServiceException(SERVICE_NAME, error.getText(), error.getCode());
             } else {
                 throw new DaServiceException(SERVICE_NAME, "Ошибка ФП Печати", "REPORT_SERVICE_ERROR");
             }
         }
         if (response.getBody() == null) {
             throw new DaServiceException(SERVICE_NAME, "Ошибка ФП Печати - пустой документ", "REPORT_SERVICE_ERROR");
         }
         eribLogger.sendIntegrationMessage(request.toString(), response.toString(),
                 config.getReportPath(), System.currentTimeMillis() - start, "Запрос и ответ от ФП Печати");
         return response.getBody();
     }
 }